package com.zyb.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.HashMap;
import java.util.Map;


public class TcpServerHandler extends ChannelInboundHandlerAdapter {
    public static Map<String, ChannelHandlerContext> channelHandlerContextMap = new HashMap<String, ChannelHandlerContext>();
    /**
     * 客户端与服务端创建连接的时候调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //System.out.println("客户端与服务端连接开始...");
        TcpNettyConfig.group.add(ctx.channel());
        channelHandlerContextMap.put(ctx.channel().id().asLongText(), ctx);
        System.out.println("连接数量："+ channelHandlerContextMap.size());
    }

    /**
     * 客户端与服务端断开连接时调用
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
       // System.out.println("客户端与服务端连接关闭...");
        TcpNettyConfig.group.remove(ctx.channel());
        channelHandlerContextMap.remove(ctx.channel().id().asLongText());
    }

    /**
     * 服务端接收客户端发送过来的数据结束之后调用
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
        //System.out.println("信息接收完毕...");
    }

    /**
     * 工程出现异常的时候调用
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //cause.printStackTrace();
        System.out.println("客户端异常关闭");
        ctx.close();
    }

    /**
     * 服务端处理客户端websocket请求的核心方法，这里接收了客户端发来的信息
     */
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object info) throws Exception {
        ByteBuf buf = (ByteBuf) info;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, "GBK");
        //System.out.println("接收客户端数据:" + body);
        ByteBuf pingMessage = Unpooled.buffer();
        pingMessage.writeBytes("ok".getBytes());
        channelHandlerContext.writeAndFlush(pingMessage);
    }
}